package com.iyao_app.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/11/10.
 */

public abstract class BaseRecyclerAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
    public Context context;
    public List<T> data = new ArrayList<>();
    private ViewGroup parent;
    public LayoutInflater mInflater;
    private OnRecyclerViewItemClickListener mOnItemClickListener = null;

    public BaseRecyclerAdapter(Context context, List<T> data) {
        super();
        this.context = context;
        if (data != null) {
            this.data = data;
        }
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public VH onCreateViewHolder(final ViewGroup parent, int viewType) {
        VH viewHolder = getViewHolder( viewType);
        this.parent = parent;
        return viewHolder;
    }

    private boolean isItemClick = true;

    public void setItemClickable(boolean isClick) {
        isItemClick = isClick;
    }

    @Override
    public void onBindViewHolder(VH holder, final int position) {
        if (isItemClick) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(parent, data, position);
                    }
                }
            });
        } else {
            holder.itemView.setClickable(false);
        }

        onBindViewHolder_(holder, position);
    }


    protected abstract VH getViewHolder(int viewType);

    protected abstract void onBindViewHolder_(VH holder, int position);

    public void clear() {
        if (data != null) {
            this.data.clear();
        }
    }

    public void append(List<T> list) {
        if (this.data != null) {
            this.data.addAll(list);
            notifyDataSetChanged();
        }
    }

    protected boolean isEnabled(int viewType) {
        return true;
    }


    @Override
    public int getItemCount() {
//        if (data.size() == 0) {
//            return 9;
//        }
        return data.size();
    }

    public void appendAll(List<T> list) {
        if (this.data != null) {
            this.data.clear();
            this.data.addAll(list);
        }
        notifyDataSetChanged();
    }

    //define interface
    public interface OnRecyclerViewItemClickListener<T> {
        void onItemClick(View view, List<T> data, int position);
    }

    public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }
}
